package com.ruoyi.web.controller.system;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.domain.WxGetInfoEntity;
import com.ruoyi.system.mapper.SysLogininforMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.tomcat.util.json.JSONParser;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wx/user")
public class WxMaUserController {
    private final WxMaService wxMaService;
    private final RedisTemplate redisTemplate;
    @Autowired
    private SysLogininforMapper logininforMapper;
    @Autowired
    private SysRegisterService registerService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 登陆接口
     */
    @GetMapping("/login")
    public String login( String code) {
        if (StringUtils.isBlank(code)) {
            return "empty jscode";
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
           // log.info(session.getSessionKey());
           // log.info(session.getOpenid());//账号唯一id，可以作为身份标识
            //TODO 可以增加自己的逻辑，关联业务相关数据
            //查找数据库了该openid存不存在，存在说明不是第一次登录，不存在则将该openid ,写入数据库，并手动生成password等信息
            Integer user = logininforMapper.findUser(session.getOpenid());
            if (user == 0){
                RegisterBody registerBody = new RegisterBody();
                registerBody.setUsername(session.getOpenid());
                registerBody.setPassword(session.getOpenid());
                registerService.register(registerBody);
            }
            String token = loginService.login(session.getOpenid(), session.getOpenid(), null, null);
            //用opendi去找存不存在token，有则返回，没有就存入新token并返回
            String fondToken = sysUserMapper.fondToken(session.getOpenid());
            if (StringUtils.isNotEmpty(fondToken)){
                token = fondToken;
            }
                //把token设置为用户的token
                sysUserMapper.updateToken(session.getOpenid(),token);
            redisTemplate.opsForValue().set(token,token);
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token",token);
            return JsonUtils.toJson(tokenMap);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return e.toString();
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @PostMapping("/getUserInfo")
    public String info(@RequestBody WxGetInfoEntity wxGetInfoEntity) {

        Object token = redisTemplate.opsForValue().get(wxGetInfoEntity.getAtoken());

        String rawData = wxGetInfoEntity.getRawData();
        JSONObject parse = JSONUtil.parseObj(rawData);
        String nickName = parse.getStr("nickName");
        String avatarUrl = parse.getStr("avatarUrl");
        String s = token.toString();
        //更新表内的nick_name为微信用户名和头像
            logininforMapper.updateUserInfo(nickName, avatarUrl, s);

        WxMaConfigHolder.remove();//清理ThreadLocal
        return JsonUtils.toJson(parse);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return JsonUtils.toJson(phoneNoInfo);
    }
}
